//
//  HZMallHttpManager.m
//  app
//
//  Created by 刘华舟 on 15/5/21.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HZMallHttpManager.h"

#import "HDGoodsCollectManager.h"

//model
#import "HZRemoteResult.h"

#import "HZHotKeyWordsData.h"
#import "HZGoodsSearchListData.h"
#import "HZCategoryGoodsListData.h"
#import "HZTemaiGoodsListData.h"
#import "HZGoodsDetailVCData.h"
#import "HZFindCategoriesData.h"
#import "HZProductCommentsVCData.h"

//tool
#import "HZMallSqlDataManager.h"
#import "SNBaseInfoManager.h"

#import "JSONKit.h"

static NSString *kMallCartHttpCookies = @"MallHttpCookies";
static NSString *const kMallNSDataIntervalFormmat = @"kMallNSDataIntervalFormmat";

static float kMallFindCategoriesDataCacheValidableTime = 1;//7*24*60*60.0f;
static float kMallHttpAfterDelayTimeInterval = 0.2f;

static HZMallHttpManager *_mallHttpManager = nil;


@interface HZMallHttpManager()

@property (strong, nonatomic) JKHttpClient *http;

@property (strong, nonatomic) AFNetworkReachabilityManager *reachabilityManager;
@property (strong, nonatomic) HZMallSqlDataManager *sqlManager;

@end

@implementation HZMallHttpManager

+ (instancetype)shareHttpRequestMananger{
    if (_mallHttpManager == nil) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _mallHttpManager = [[self alloc] initManager];
        });
    }
    return _mallHttpManager;
}

- (instancetype)initManager{
    if (self = [super init]) {
        self.http = [[JKHttpClient alloc] init];
        self.sqlManager = [HZMallSqlDataManager defaultManager];
        self.reachabilityManager = [AFNetworkReachabilityManager sharedManager];
    }
    _mallHttpManager = self;
    return _mallHttpManager;
}
//是否网络通
- (BOOL)networkReachable{
    return self.reachabilityManager.isReachable;
}

/*************************商城分类****************************/
//加载热搜词汇
- (void)loadHotSearchKeyWordsWithResult:(HZRemoteResult *)remote{
    
    //从数据库中预先加载数据
    NSDictionary *dict = [self.sqlManager loadHotKeywordsData];
    
    if (dict && dict.count > 0) {
        NSString *dataTimeStamp = [self.sqlManager queryHotKeywordsTimeStamp];
        HZHotKeyWordsData *hotKeywordsData = nil;
        if (dict.count > 0) {
            hotKeywordsData = [HZHotKeyWordsData dataWithDictionary:dict];
            remote.info = hotKeywordsData;
        }
        hotKeywordsData.message = @"ok";
        hotKeywordsData.timestamp = dataTimeStamp;
        NSDictionary *responeDict = @{@"ret":@0, @"msg":@"ok", @"result":[dict objectForKey:APIKEY_mall_result], @"timestamp":dataTimeStamp};
        NSMutableData *data = [[NSMutableData alloc] init];
        //NSDictionary字典转NSData
        NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
        [archiver encodeObject:responeDict forKey:kMallNSDataIntervalFormmat];
        [archiver finishEncoding];
        
        JKResponse *resultRespone = [[JKResponse alloc] initWithResponse:data req:nil];
        [remote call:resultRespone];
        
        
        float time = ([NSDate date].timeIntervalSince1970-[[[SNBaseInfoManager shareManager] baseInfoObjectForKey:kHZTimeOffsetBetweenServerAndLocal] floatValue] - [dataTimeStamp floatValue]);
        if ( time < kMallHotKeyWordsDataCacheValidableTime) {
            return;
        }
        
    }
    
    
    [self.http showNetUnReachableToast];
    
    //发起请求之前先取消之前的请求
    [self.http cancel:[SNUniteUrl shareUniteUrl].sbgd_searchGoodsUrl];
    
    //请求数据
    [self.http post:[SNUniteUrl shareUniteUrl].sbgd_searchGoodsUrl params:nil
             result:^(JKResponse *result) {
                 
                 if (result.OK) {
                     HZHotKeyWordsData *hotKeywordsData = [HZHotKeyWordsData dataWithDictionary:result.content];
                     //服务器时间戳
                     NSTimeInterval serverTimeInterval = [NSDate date].timeIntervalSince1970-[[[SNBaseInfoManager shareManager] baseInfoObjectForKey:kHZTimeOffsetBetweenServerAndLocal] floatValue];
                     hotKeywordsData.message = result.message;
                     hotKeywordsData.timestamp = [NSString stringWithFormat:@"%f", serverTimeInterval];
                     
                     remote.info = hotKeywordsData;
                     
                     
                     
                     //save data to disk here
                     [self.sqlManager updateHotKeyWordsCacheWithData:result.content];
                     
                 }
                 [remote call:result];
             }];
}

//搜索商品
- (void)searchGoodsWithParams:(NSDictionary *)params result:(HZRemoteResult *)remote{
    
    [self.http showNetUnReachableToast];
    
    //发起请求之前先取消之前的请求
    [self.http cancel:[SNUniteUrl shareUniteUrl].sbgd_searchGoodsUrl];
    
    //请求数据
    [self.http post:[SNUniteUrl shareUniteUrl].sbgd_searchGoodsUrl params:params
             result:^(JKResponse *result) {
                 
                 if (result.OK) {
                     HZGoodsSearchListData *goodsSearchListData = [HZGoodsSearchListData dataWithDictionary:result.content];
                     goodsSearchListData.message = result.message;
                     goodsSearchListData.timestamp = [NSString stringWithFormat:@"%ld", result.timestamp];
                     goodsSearchListData.pageNum = @"1";
                     remote.info = goodsSearchListData;
                     
                     if (result.status == JKResponseTail) {
                         goodsSearchListData.noMoreData = YES;
                     }
                     
                     goodsSearchListData.pageNum = @"1";
                 }
                 [remote call:result];
             }];
}

//搜索商品
- (void)loadMoreSearchGoodsWithParams:(NSDictionary *)params result:(HZRemoteResult *)remote{
    
    [self.http showNetUnReachableToast];
    
    //发起请求之前先取消之前的请求
    [self.http cancel:[SNUniteUrl shareUniteUrl].sbgd_searchGoodsUrl];
    
    //请求数据
    [self.http post:[SNUniteUrl shareUniteUrl].sbgd_searchGoodsUrl params:params
             result:^(JKResponse *result) {
                 
                 if (result.OK) {
                     
                     HZGoodsSearchListData *data = (HZGoodsSearchListData *)remote.info;
                     NSArray *goodArray = [result.content arrayForKey:APIKEY_mall_result];
                     if (result.isTail && goodArray.count <= 0) {
                         data.noMoreData = YES;
                         remote.info = data;
                     }else{
                         data.pageNum = [NSString stringWithFormat:@"%d", [data.pageNum integerValue]+1];
                         [data addMoreDataWithArray:goodArray];
                         
                         remote.info = data;
                     }
                     
                 }
                 [remote performSelector:@selector(call:) withObject:result afterDelay:kMallHttpAfterDelayTimeInterval];
             }];
}



//加载某分类下商品列表
- (void)loadCategoryGoodsListWithParams:(NSDictionary *)params result:(HZRemoteResult *)remote{
    [self.http showNetUnReachableToast];
    
    //发起请求之前先取消之前的请求
    [self.http cancel:[SNUniteUrl shareUniteUrl].static_categoryGoodsListUrl];
    
    //请求数据
  
    [self.http get:[SNUniteUrl shareUniteUrl].static_categoryGoodsListUrl params:params
             result:^(JKResponse *result) {
                 
                 if (result.OK) {
                     HZCategoryGoodsListData *goodsSearchListData = [HZCategoryGoodsListData dataWithDictionary:result.content];
                     goodsSearchListData.message = result.message;
                     goodsSearchListData.timestamp = [NSString stringWithFormat:@"%ld", result.timestamp];
                     goodsSearchListData.pageNum = @"1";
                     remote.info = goodsSearchListData;
                     
                 }
                 [remote performSelector:@selector(call:) withObject:result afterDelay:kMallHttpAfterDelayTimeInterval];
             }];
}
//加载更多某分类下商品活动列表
- (void)loadMoreCategoryGoodsListWithParams:(NSDictionary *)params result:(HZRemoteResult *)remote{
    [self.http showNetUnReachableToast];
    
    //发起请求之前先取消之前的请求
    [self.http cancel:[SNUniteUrl shareUniteUrl].static_categoryGoodsListUrl];
    
    //请求数据
    [self.http get:[SNUniteUrl shareUniteUrl].static_categoryGoodsListUrl params:params
             result:^(JKResponse *result) {
                 
                 if (result.OK) {
                     
                     HZCategoryGoodsListData *data = (HZCategoryGoodsListData *)remote.info;

                     NSArray *goodArray = [result.content arrayForKey:APIKEY_mall_products_list];
                     
                     if (result.isTail && goodArray.count <= 0) {
                         data.noMoreData = YES;
                         remote.info = data;
                     }else{
                         data.pageNum = [NSString stringWithFormat:@"%d", [data.pageNum integerValue]+1];
                         [data addMoreDataWithArray:goodArray];
                         
                         remote.info = data;
                     }
                     
                 }
                 [remote performSelector:@selector(call:) withObject:result afterDelay:kMallHttpAfterDelayTimeInterval];
                 //[remote call:result];
             }];
}


//加载特卖商品列表
- (void)loadTeMaiGoodsListWithParams:(NSDictionary *)params result:(HZRemoteResult *)remote{
    [self.http showNetUnReachableToast];
    
    //发起请求之前先取消之前的请求
    [self.http cancel:[SNUniteUrl shareUniteUrl].static_temaiGoodsListUrl];
    
    //请求数据
    
    [self.http get:[SNUniteUrl shareUniteUrl].static_temaiGoodsListUrl params:params
            result:^(JKResponse *result) {
                
                if (result.OK) {
                    
                    HZTemaiGoodsListData *goodsSearchListData = [HZTemaiGoodsListData dataWithDictionary:result.content];
                    goodsSearchListData.message = result.message;
                    goodsSearchListData.timestamp = [NSString stringWithFormat:@"%ld", result.timestamp];
                    
                    // offset =本地时间 - 服务器时间
                    goodsSearchListData.timeoffset = [[[SNBaseInfoManager shareManager] baseInfoObjectForKey:kHZTimeOffsetBetweenServerAndLocal] floatValue];
                    
                    goodsSearchListData.pageNum = @"1";
                    remote.info = goodsSearchListData;
                    
                    if (result.status == JKResponseTail) {
                        goodsSearchListData.noMoreData = YES;
                    }
                    
                }
                [remote performSelector:@selector(call:) withObject:result afterDelay:kMallHttpAfterDelayTimeInterval];
            }];
}
//加载更多特卖商品活动列表
- (void)loadMoreTeMaiGoodsListWithParams:(NSDictionary *)params result:(HZRemoteResult *)remote{
    [self.http showNetUnReachableToast];
    
    //发起请求之前先取消之前的请求
    [self.http cancel:[SNUniteUrl shareUniteUrl].static_temaiGoodsListUrl];
    
    //请求数据
    [self.http get:[SNUniteUrl shareUniteUrl].static_temaiGoodsListUrl params:params
            result:^(JKResponse *result) {
                
                if (result.OK) {
                    
                    HZTemaiGoodsListData *data = (HZTemaiGoodsListData *)remote.info;
                    NSArray *goodArray = [result.content arrayForKey:APIKEY_mall_products_list];
                    
                    if (result.isTail && goodArray.count <= 0) {
                        data.noMoreData = YES;
                        remote.info = data;
                    }else{
                        data.pageNum = [NSString stringWithFormat:@"%d", [data.pageNum integerValue]+1];
                        [data addMoreDataWithArray:goodArray];
                        
                        remote.info = data;
                    }
                    
                    // offset =本地时间 - 服务器时间
                    data.timeoffset = [[[SNBaseInfoManager shareManager] baseInfoObjectForKey:kHZTimeOffsetBetweenServerAndLocal] floatValue];
                    
                }
                [remote call:result];
            }];
}


//加载某商品的详情数据
- (void)loadGoodsDetailsWithParams:(NSDictionary *)params result:(HZRemoteResult *)remote{
    [self.http showNetUnReachableToast];
    
    //发起请求之前先取消之前的请求
    [self.http cancel:[SNUniteUrl shareUniteUrl].static_detailpageUrl];
    
    //请求数据
    [self.http get:[SNUniteUrl shareUniteUrl].static_detailpageUrl params:params
             result:^(JKResponse *result) {
                 
                 if (result.OK) {
                     
                     HZGoodsDetailVCData *detailData = [[HZGoodsDetailVCData alloc] initWithJSONData:result.content];
                     
                     //判断该商品是否已经被收藏
                     HDGoodsCollectManager *collectManager = [HDGoodsCollectManager shareManager];
                     if ([collectManager productIsExist:detailData.headModel.topModel.productID]) {
                         detailData.headModel.topModel.collection = YES;
                     }
                     
                     detailData.message = result.message;
                     detailData.timestamp = [NSString stringWithFormat:@"%ld", result.timestamp];
                     remote.info = detailData;
                 }
                 [remote performSelector:@selector(call:) withObject:result afterDelay:kMallHttpAfterDelayTimeInterval];
            
             }];
    
}

//把商品添加到收藏
- (void)addProductToFavoriteWithParams:(NSDictionary *)params resutl:(HZRemoteResult *)remote{
    [self.http showNetUnReachableToast];
    
    //发起请求之前先取消之前的请求
    [self.http cancel:[SNUniteUrl shareUniteUrl].static_detailpageUrl];
    
    //请求数据
    [self.http get:[SNUniteUrl shareUniteUrl].sbpd_addProductToMyCollectionUrl params:params
            result:^(JKResponse *result) {
                [remote call:result];
            }];
    

}


//加载某商品评论列表
- (void)loadProductCommentsListWithParams:(NSDictionary *)params result:(HZRemoteResult *)remote{
    [self.http showNetUnReachableToast];
    
    //发起请求之前先取消之前的请求
    [self.http cancel:[SNUniteUrl shareUniteUrl].sbgd_productCommentsUrl];
    
    //请求数据
    [self.http get:[SNUniteUrl shareUniteUrl].sbgd_productCommentsUrl params:params
              result:^(JKResponse *result) {
                  
                  if (result.OK) {
                      HZProductCommentsVCData *data = [HZProductCommentsVCData dataWithDictionary:result.content];
                      data.message = result.message;
                      data.timestamp = [NSString stringWithFormat:@"%ld", result.timestamp];
                      remote.info = data;
                      
                  }
                  [remote call:result];
              }];
}
//加载更多某商品评论列表
- (void)loadMoreProductCommentsListWithParams:(NSDictionary *)params result:(HZRemoteResult *)remote{
    [self.http showNetUnReachableToast];
    
    //发起请求之前先取消之前的请求
    [self.http cancel:[SNUniteUrl shareUniteUrl].sbgd_productCommentsUrl];
    
    //请求数据
    [self.http get:[SNUniteUrl shareUniteUrl].sbgd_productCommentsUrl params:params
              result:^(JKResponse *result) {
                  
                  if (result.OK) {
                      
                      HZProductCommentsVCData *data = (HZProductCommentsVCData *)remote.info;
                      if (result.isTail && [result.content arrayForKey:APIKEY_mall_comments].count <= 0) {
                          data.noMoreData = YES;
                          remote.info = data;
                      }else{
                          
                          [data addMoreDataWithArray:[result.content arrayForKey:APIKEY_mall_comments]];
                          
                          remote.info = data;
                      }
                      
                  }
                  [remote call:result];
              }];
}


////加载更多某商品评论列表
//- (void)loadMoreProductCommentsListWithParams:(NSDictionary *)params result:(HZRemoteResult *)remote{
//    [self.http showNetUnReachableToast];
//    
//    //发起请求之前先取消之前的请求
//    [self.http cancel:[SNUniteUrl shareUniteUrl].sbgd_productCommentsUrl];
//    
//    //请求数据
//    [self.http get:[SNUniteUrl shareUniteUrl].sbgd_productCommentsUrl params:params
//            result:^(JKResponse *result) {
//                
//                if (result.OK) {
//                    
//                     HZGoodsDetailVCData*data = (HZGoodsDetailVCData *)remote.info;
//                    if (result.isTail && [result.content arrayForKey:APIKEY_mall_comments].count <= 0) {
//                        data.noMoreData = YES;
//                        remote.info = data;
//                    }else{
//                        
//                        [data addMoreDataWithArray:[result.content arrayForKey:APIKEY_mall_comments]];
//                        
//                        remote.info = data;
//                    }
//                    
//                }
//                [remote call:result];
//            }];
//}
//

//加载商品分类
- (void)loadFindGoodsCategoriesWithParams:(NSDictionary *)params result:(HZRemoteResult *)remote{
    
    
    //从数据库中预先加载数据
    NSDictionary *dict = [self.sqlManager loadFindCategoriesData];
    
    if (dict && dict.count > 0) {
        NSString *dataTimeStamp = [self.sqlManager queryFindCategoriesTimeStamp];
        NSString *url = [self.sqlManager queryFindCategoriesURL];
        HZFindCategoriesData *findCategoriesData = nil;
        if (dict.count > 0) {
            findCategoriesData = [HZFindCategoriesData dataWithDictionary:dict];
            remote.info = findCategoriesData;
        }
        findCategoriesData.message = @"ok";
        findCategoriesData.timestamp = dataTimeStamp;
        NSDictionary *responeDict = @{@"ret":@0, @"msg":@"ok", @"result":dict, @"timestamp":dataTimeStamp};
        NSMutableData *data = [[NSMutableData alloc] init];
        //NSDictionary字典转NSData
        NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
        [archiver encodeObject:responeDict forKey:kMallNSDataIntervalFormmat];
        [archiver finishEncoding];
        
        JKResponse *resultRespone = [[JKResponse alloc] initWithResponse:data req:nil];
        [remote call:resultRespone];
        
        float time = ([NSDate date].timeIntervalSince1970-[[[SNBaseInfoManager shareManager] baseInfoObjectForKey:kHZTimeOffsetBetweenServerAndLocal] floatValue] - [dataTimeStamp floatValue]);
        if ([url isEqualToString:[SNUniteUrl shareUniteUrl].static_catogarypageUrl] && time < kMallFindCategoriesDataCacheValidableTime ) {
            return;
        }
    }
    
    [self.http showNetUnReachableToast];
    
    //发起请求之前先取消之前的请求
    [self.http cancel:[SNUniteUrl shareUniteUrl].static_catogarypageUrl];

    NSString * myAreaID = [[NSUserDefaults standardUserDefaults] objectForKey:kMyAreaID] && [[[NSUserDefaults standardUserDefaults] objectForKey:kMyAreaID] length] ? [[NSUserDefaults standardUserDefaults] objectForKey:kMyAreaID] : @"0";
    //请求数据
    [self.http get:[SNUniteUrl shareUniteUrl].static_catogarypageUrl params:@{@"cmid":myAreaID}

             result:^(JKResponse *result) {
                 
                 if (result.OK) {
                     HZFindCategoriesData *data = [[HZFindCategoriesData alloc] initDataWithDictionary:result.content];
                     
                     //保存数据
                     [self.sqlManager updateFindCategoriesWithData:result.content];
                     
                     //服务器时间戳
                     NSTimeInterval serverTimeInterval = [NSDate date].timeIntervalSince1970-[[[SNBaseInfoManager shareManager] baseInfoObjectForKey:kHZTimeOffsetBetweenServerAndLocal] floatValue];
                     data.message = result.message;
                     data.timestamp = [NSString stringWithFormat:@"%f", serverTimeInterval];
                     remote.info = data;
                 }
                 [remote call:result];
             }];
}


//向购物车里面添加商品
- (void)addProductToCartWithParams:(NSDictionary *)params result:(HZRemoteResult *)remote needBuyNow:(BOOL) isBuyNow{
    [self.http showNetUnReachableToast];
    
    //发起请求之前先取消之前的请求
    [self.http cancel:[SNUniteUrl shareUniteUrl].sbpd_addProductToMyCartUrl];
    
    //请求数据

    [self.http get:[SNUniteUrl shareUniteUrl].sbpd_addProductToMyCartUrl params:params
              result:^(JKResponse *result) {
                  
                  if (result.OK) {
                      //存数据库
                  }
                  [remote call:result];
              }];
}

@end
